package org.eyeTopLight.controller;

import com.alibaba.fastjson.JSONObject;
import org.eyeTopLight.po.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * LoginController只负责登陆相关动作，采用jwt token，登出本地清除token即可
 */
@RestController
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private RestTemplate restTemplate;
    /**
     * @title login 登录操作
     */
    @GetMapping(value = "/login/login")
    public CommonResult login(@RequestParam("name") String user_phone,
                              @RequestParam("pwd") String password){

        /**
         * 获取access_token
         */
        logger.info("用户" + user_phone + "开始登陆");
        try{
            String loginUrl = "http://localhost:8080/oauth/token?client_id=basic&client_secret=basic&grant_type=password&username="+ user_phone +"&password="+password;
            JSONObject tokenInfo = restTemplate.postForObject(loginUrl,null,JSONObject.class);
            String jwtToken = (String) tokenInfo.get("access_token");
            if(null == jwtToken){
                return new CommonResult(401,"用户名或密码错误");
            }
            return new CommonResult(200,"login success",jwtToken);
        }catch (Exception e){
            logger.error("登陆操作异常",e);
            return new CommonResult(500,"服务器内部错误");
        }
    }

    @GetMapping(value = "/login/logout")
    @CrossOrigin
    public CommonResult logout() {
        System.out.println("调用了自定义的logout");
        return new CommonResult(403,"jwt令牌过期");
    }

    @GetMapping(value = "/login/verifyToken")
    public CommonResult verifyToken(){
        return new CommonResult(200,"jwt令牌有效");
    }

}
